<template>
  <view :class="theme">
    <view class="main">
      <block v-for="(option, key) in (options[optionKey] as AnyObject)" :key="key">
        <view v-if="option.title" class="mb-60">
          <label class="mb-20 fs-28">{{ option?.title }}</label>
          <u-image v-if="key === 'qrCode'" @click="chooseImage" radius="10" width="200" height="200"
            :src="option.value || option.showValue || `/static/img/otc/img-addPicture.png`" />
          <input v-else v-model="option.value" :disabled="!+currentStatus" class="bg-21 height-88 br-10 pl-20 pr-20 fs-28"
            type="text" :placeholder="option.errorMessage" />
        </view>
      </block>
    </view>

    <view class="footer bg-21">
      <button @click="beforeSave" :disabled="!+currentStatus" hover-class="tap-hover"
        class="fs-36 fw-700 br-50 color-2 bg-23" style="line-height: 44px; margin: 16px 50rpx;">
        {{ currentStatus ? "保存" : "审核中..." }}
      </button>
    </view>

    <u-popup v-model="showPopup.captcha" @input="changePopup($event, 'captcha')" mode="center" closeable
      :mask-close-able="false" close-icon-color="#fff">
      <view class="br-20 bg-21 p-30" style="width: 600rpx;">
        <label class="fs-36 fw-700">验证手机号</label>
        <text class="mt-30">请发送短信验证码到手机</text>
        <text class="mt-20 fs-32">{{ formatPhoneNumber(userInfo.mobile) }}</text>
        <view class="mt-30 fd-row ai-center bg-21 br-20">
          <input v-model="captcha.value" class="f1 color-2 pl-30 pr-30 height-88" placeholder="请输入验证码" type="number"
            maxlength="6" placeholder-class="color-9">
          <button @click="getCaptcha" :disabled="captcha.disabled" hover-class="tap-hover"
            class="m-0 p-0 fs-24 color-2 border-none" plain>
            <label class="jc-center" style="width: 160rpx; height: 40rpx; border-left: #999 2rpx solid;">
              {{ captcha.text }}
            </label>
          </button>
        </view>
        <button @click="save" :disabled="!captcha.value" class="mt-50 fs-36 fw-700 br-50 color-2 bg-23"
          hover-class="tap-hover" style="line-height: 44px; width: 540rpx;">确认</button>
      </view>
    </u-popup>
  </view>
</template>

<script lang="ts" setup>

import { useMapState } from "@/common/libs/store";
import { debounce, formatPhoneNumber, sleep } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};

const showPopup = reactive({
  captcha: false,
});

const options = reactive({
  weChat: {
    name: {
      title: "姓名",
      errorMessage: "请输入姓名",
      value: "",
    },
    account: {
      title: "微信账号",
      errorMessage: "请输入微信账号",
      value: ""
    },
    qrCode: {
      title: "收款二维码",
      errorMessage: "请上传收款二维码",
      value: "",
      showValue: "",
    },
  },
  aliPay: {
    name: {
      title: "姓名",
      errorMessage: "请输入姓名",
      value: ""
    },
    account: {
      title: "支付宝账号",
      errorMessage: "请输入支付宝账号",
      value: ""
    },
    qrCode: {
      title: "收款二维码",
      errorMessage: "请上传收款二维码",
      value: "",
      showValue: "",
    },
  },
  bankCard: {
    name: {
      title: "姓名",
      errorMessage: "请输入姓名",
      value: ""
    },
    account: {
      title: "银行账号/卡号",
      errorMessage: "请输入银行账号",
      value: ""
    },
    bank: {
      title: "银行名称",
      errorMessage: "请输入银行名称",
      value: ""
    },
    origin: {
      title: "开户支行（选填）",
      errorMessage: "请输入开户支行",
      value: ""
    },
  },
  usdt: {
    name: {
      errorMessage: "兼容接口username字段",
      value: "钱包地址",
    },
    account: {
      title: "USDT钱包地址",
      errorMessage: "请输入USDT钱包地址",
      value: "",
    }
  }
});
const optionKey = ref<keyof typeof options>("weChat");
const mapKey = { aliPay: 1, weChat: 2, bankCard: 3, usdt: 4 };
const userInfo = ref<AnyObject>({});
const captcha = reactive({
  text: "获取验证码",
  errorMessage: "验证码输入有误",
  disabled: false,
  count: 60,
  timer: null as any,
  value: "",
  field: "code",
  rule: /^[0-9]{4,8}$/
});
const currentStatus = ref(-1);
let isModify = 0;
onLoad(({ type }: any) => {
  type && (optionKey.value = type);
  uni.getStorage({
    key: $config.STORAGE_KEY_USER_INFO,
    success(data) {
      userInfo.value = data;
    }
  });
  uni.request({
    url: "/accountDetail",
    data: { id: mapKey[optionKey.value] },
    success({ data }: any) {
      if (!data) return;
      const option: AnyObject = options[optionKey.value];
      option.account && (option.account.value = data.number || "");
      option.name?.title && (option.name.value = data.username || "");
      option.qrCode && (option.qrCode.value = data.url || "");
      option.bank && (option.bank.value = data.bank_name || "");
      option.origin && (option.origin.value = data.bank_address || "");
      (data.status || data.status === 0) && (currentStatus.value = +data.status);
      (data.status && data.number) && (isModify = 1);
    }
  });
});

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey] = e;
}

const chooseImage = () => {
  if (!+currentStatus.value) {
    uni.showToast({ title: "系统审核中...", icon: "none" });
    return;
  }

  uni.chooseImage({
    count: 1,
    sourceType: ["album"],
    sizeType: ["compressed"],
    success({ tempFilePaths }) {
      options[optionKey.value as "weChat" || "aliPay"].qrCode.showValue = tempFilePaths[0];
      options[optionKey.value as "weChat" || "aliPay"].qrCode.value = "";
    }
  });
}

const countDown = () => {
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  }
  captcha.timer = setInterval(intervalTask(), 1000);
}

const getCaptcha = () => {
  if (captcha.disabled) return;
  uni.showToast({ icon: "loading", mask: true });
  countDown();
  uni.request({
    url: "/sendSms",
    data: { mobile: userInfo.value.mobile, type: "verify" },
    success: () => uni.showToast({ title: "发送成功", icon: "none" })
  });
}

const beforeSave = debounce(() => {
  const option: AnyObject = options[optionKey.value];

  if (!+currentStatus.value) {
    uni.showToast({ title: "系统审核中...", icon: "none" });
    return;
  }

  if (option.name && !option.name.value) {
    uni.showToast({ title: option.name.errorMessage, icon: "none" });
    return;
  }
  if (option.account && !option.account.value) {
    uni.showToast({ title: option.account.errorMessage, icon: "none" });
    return;
  }

  if (["weChat", "aliPay"].includes(optionKey.value) && !(option.qrCode.value || option.qrCode.showValue)) {
    uni.showToast({ title: option.qrCode.errorMessage, icon: "none" });
    return;
  }
  if (["bankCard"].includes(optionKey.value) && !option.bank.value) {
    uni.showToast({ title: option.bank.errorMessage, icon: "none" });
    return;
  }

  if (isModify) {
    showPopup.captcha = true;
    return;
  }

  save();
});

const save = () => {
  const option: AnyObject = options[optionKey.value];

  function submit(url?: string) {
    uni.showToast({ icon: "loading" });
    uni.request({
      url: "/accountUpdate",
      data: {
        username: option.name?.value,
        number: option.account?.value,
        type: mapKey[optionKey.value],
        url: url || option.qrCode?.value || null,
        bank_name: option.bank?.value,
        bank_address: option.origin?.value,
        code: captcha.value
      },
      async success() {
        uni.showToast({ title: "提交成功" });
        await sleep(1.2);
        uni.navigateBack();
      }
    });
  }

  if (option.qrCode?.showValue) {
    uni.showToast({ icon: "loading" });
    uni.uploadFile({
      url: $config.API_FILE_UPLOAD,
      filePath: option.qrCode.showValue,
      formData: { type: "", position: "avatar" },
      name: "file",
      success({ data }: any) {
        uni.hideToast();
        submit(data[0]);
      }
    });
    return;
  }
  submit();
}

</script>
<style lang="scss">
page {
  background-color: $uni-bg-color-otc;
  color: $uni-text-color-otc;
}
</style>
<style lang="scss" scoped>
// scss
button[disabled] {
  background-color: transparent;
}

.main {
  padding: 30rpx 30rpx 80px;
  border-radius: 32rpx 32rpx 0 0;
}


.footer {
  position: fixed;
  z-index: 99;
  bottom: 0;
  left: var(--window-left);
  right: var(--window-right);
}
</style>